package icom.acm.manager;

import icom.acm.bean.T_POSITION;
import icom.acm.util.DBConnect;

import java.sql.Statement;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

public class T_PositionMgr {
	public int insert(final T_POSITION pos){
		int flag = -1;
		String sql = "insert into T_POSITION(P_ID,P_NAME) values(NULL, ?)";
		DBConnect db = new DBConnect();
		db.setAutoCommit(false);
		db.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);		
		db.setString(1, pos.getP_NAME());
		try {
			db.excute();
			flag = db.getGeneratedKeys();
			db.commit();
		} catch (MySQLIntegrityConstraintViolationException e) {
			// 数据重复
			flag = -1;
		} finally{
			db.setAutoCommit(true);
			db.close();
		}
		return flag;
	}
	
	public int update(final T_POSITION pos){
		int flag = -1;
		String sql = "UPDATE T_POSITION SET P_NAME=? WHERE P_ID=?";
		DBConnect db = new DBConnect();
		db.setAutoCommit(false);
		db.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
		db.setString(1, pos.getP_NAME());
		try {
			db.excute();
			flag = db.getGeneratedKeys();
			db.commit();
		} catch (MySQLIntegrityConstraintViolationException e) {
			// 数据重复
			flag = -1;
		} finally{
			db.setAutoCommit(true);
			db.close();
		}
		return flag;
	}
	public void delete(final int pid){
		final DBConnect db = new DBConnect();
		final String sql = "DELETE FROM T_POSITION WHERE P_ID = ?";
		System.out.println(sql);
		db.setAutoCommit(false);
		db.prepareStatement(sql);
		db.setInt(1, pid);
		try {
			db.excute();
			db.commit();
		} catch (final Exception ex) {
			ex.printStackTrace();
		} finally {
			db.setAutoCommit(true);
			db.close();
		}
	}
}
